package com.mintuo.litecomposite.common.util;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;

public final class Sm4Utils {
    private Sm4Utils() {
    }

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ENCODING = "UTF-8";

    private static final String ALGORITHM_NAME = "SM4";

    /**
     * PKCS5Padding  NoPadding 补位规则，PKCS5Padding缺位补0，NoPadding不补
     */
    private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";

    // 128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * ECB加密模式，无向量
     * @param algorithmName 算法名称
     * @param mode          模式
     * @param key           key
     * @return 结果
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * 自动生成密钥
     * @explain
     * @return
     */

    public static byte[] generateKey() throws Exception {

        return generateKey(DEFAULT_KEY_SIZE);

    }

    public static String generateKeyString() throws Exception {

        byte[] bkey = generateKey(DEFAULT_KEY_SIZE);
        return ByteUtils.toHexString(bkey);
    }

    /**

     * @explain

     * @param keySize

     * @return

     * @throws Exception

     */

    public static byte[] generateKey(int keySize) throws Exception {

        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);

        kg.init(keySize, new SecureRandom());

        return kg.generateKey().getEncoded();

    }


    /**
     * sm4加密
     * 加密模式：ECB 密文长度不固定，会随着被加密字符串长度的变化而变化
     *
     * @param hexKey   16进制密钥（忽略大小写）
     * @param plainText 待加密字符串
     * @return 返回base64编码字符串
     */
    public static String encryptEcb(String hexKey, String plainText) {
        try {
            String cipherText = "";
            // 16进制字符串-->byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // String-->byte[]
            byte[] srcData = plainText.getBytes(ENCODING);
            // 加密后的数组
            byte[] cipherArray = encryptEcbPadding(keyData, srcData);
            // byte[]-->base64String
            cipherText = Base64.encodeBase64String(cipherArray);
            return cipherText;
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * 加密模式之Ecb
     *
     * @param key 秘钥
     * @param data 待加密的数据
     * @return 字节数组
     */
    private static byte[] encryptEcbPadding(byte[] key, byte[] data) {
        try {
            //声称Ecb暗号,通过第二个参数判断加密还是解密
            Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(data);
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    //解密****************************************

    /**
     * sm4解密
     *
     * 解密模式：采用ECB
     * @param hexKey     16进制密钥
     * @param cipherText base64编码字符串
     * @return 解密后的字符串
     */
    public static String decryptEcb(String hexKey, String cipherText) {
        try {
            // 用于接收解密后的字符串
            String decryptStr = "";
            // hexString-->byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // base64String-->byte[]
            byte[] cipherData = Base64.decodeBase64(cipherText);
            // 解密
            byte[] srcData = decryptEcbPadding(keyData, cipherData);
            // byte[]-->String
            decryptStr = new String(srcData, ENCODING);
            return decryptStr;
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * 解密
     *
     * @param key 秘钥
     * @param cipherText 密文
     * @return 结果
     */
    private static byte[] decryptEcbPadding(byte[] key, byte[] cipherText) {
        try {
            //生成Ecb暗号,通过第二个参数判断加密还是解密
            Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(cipherText);
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    public static void main(String[] args) {
        String key = "";
        try{
            key = Sm4Utils.generateKeyString();
        }catch (Exception ex){

        }
        String str = "fasdfasfasdfsadfDD123456";
        String strencrypt = Sm4Utils.encryptEcb(key,str);
        String decrypt = Sm4Utils.decryptEcb(key,strencrypt);
        System.out.println("key: "+key);//70f66f53f6f11cb5f5b697cb0e33d89b
        System.out.println("orgin: "+str);
        System.out.println("strencrypt: "+strencrypt);
        System.out.println("decrypt: "+decrypt);

    }
}
